package com.qd.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.pay.domain.OrderReportNotifyDTO;
import com.qd.pay.model.OrderReportNotify;
import com.qd.pay.repository.OrderReportNotifyRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderReportNotifyService {

    private final OrderReportNotifyRepository orderReportNotifyRepository;
    @Resource
    private RedisTemplateUtil<OrderReportNotify> redisTemplateUtil;

    private static final String PREFIX_ID = "m_order_report_notify_nid_{0}";
    public List<OrderReportNotify> getList(QueryWrapper<OrderReportNotify> queryWrapper){
        return orderReportNotifyRepository.getBaseMapper().selectList(queryWrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    public OrderReportNotify save(OrderReportNotify model) throws ApiException {
        try {
            if (!orderReportNotifyRepository.save(model)) {
                throw new ApiException(ApiResult.error());
            }
            return model;
        } finally {
            clearCache(model);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(OrderReportNotify model) throws ApiException {
        OrderReportNotify historyModel = Optional.ofNullable(getById(model.getNid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        try {
            if (!orderReportNotifyRepository.updateById(model)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean removeById(String nid) throws ApiException {
        OrderReportNotify historyModel = Optional.ofNullable(getById(nid)).orElseThrow(() -> new ApiException("ID不存在,不能删除"));
        try {
            if (!orderReportNotifyRepository.removeById(nid)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    public Boolean isExists(String nid) {
        return orderReportNotifyRepository.isExists(nid);
    }

    public OrderReportNotify getById(String nid) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, nid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY * 3), () -> orderReportNotifyRepository.getById(nid), OrderReportNotify.class);
    }

    public IPage<OrderReportNotify> page(Page<OrderReportNotify> page) {
        return page(page, null);
    }

    public IPage<OrderReportNotify> page(Page<OrderReportNotify> page, OrderReportNotify model) {
        QueryWrapper<OrderReportNotify> queryWrapper = new QueryWrapper<>();
        if (null != model) {
            queryWrapper.setEntity(model);
        }
        return orderReportNotifyRepository.page(page, queryWrapper);
    }

    private void clearCache(OrderReportNotify model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getNid());
        redisTemplateUtil.deleteByKey(key);
    }

    public OrderReportNotifyDTO modelToDto(OrderReportNotify model) {
        if (null == model) {
            return null;
        }
        OrderReportNotifyDTO dto = new OrderReportNotifyDTO();
        dto.setNid(model.getNid());
        dto.setOrderId(model.getOrderId());
        dto.setOutTradeNo(model.getOutTradeNo());
        dto.setThirdPartyOrder(model.getThirdPartyOrder());
        dto.setNotifyBody(model.getNotifyBody());
        dto.setNotifyUrl(model.getNotifyUrl());
        dto.setAddTime(model.getAddTime());
        model.freeData();
        return dto;
    }

    public OrderReportNotify dtoToModel(OrderReportNotifyDTO dto) {
        if (null == dto) {
            return null;
        }
        OrderReportNotify model = new OrderReportNotify();
        model.setNid(dto.getNid());
        model.setOrderId(dto.getOrderId());
        model.setOutTradeNo(dto.getOutTradeNo());
        model.setThirdPartyOrder(dto.getThirdPartyOrder());
        model.setNotifyBody(dto.getNotifyBody());
        model.setNotifyUrl(dto.getNotifyUrl());
        model.setAddTime(dto.getAddTime());
        dto.freeData();
        return model;
    }

}